import { createRouter, createWebHashHistory } from "vue-router";
import { useUserStore } from "../store/userStore";

// 懒加载组件

const routes = [
  {
    path: "/",
    name: "Home",
    component: () => import("@/pages/Home.vue"),
  },
  {
    path: "/todo",
    name: "Todo",
    component: () => import("@/pages/Blog/Todo.vue"),
    meta: { requireAuth: true }, // 需要登录
  },
  {
    path: "/login",
    name: "Login",
    component: () => import("@/pages/User/loginPage.vue"),
  },
  {
    path: "/register",
    name: "Register",
    component: () => import("@/pages/User/RegisterPage.vue"),
  },
  {
    path: "/profile",
    name: "Profile",
    component: () => import("@/pages/User/ProfilePage.vue"),
    meta: { requireAuth: true }, // 需要登录
  },
  {
    path: "/profile/change",
    name: "ProfileChange",
    component: () => import("@/components/ProfileChange.vue"),
    meta: { requireAuth: true }, // 需要登录
  },
  {
    path: "/profile/upadte",
    name: "Profile / UpDate",
    component: () => import("@/pages/User/ProfilePage.vue"),
    meta: { requireAuth: true }, // 需要登录
  },
];

const router = createRouter({
  history: createWebHashHistory(),
  routes,
});

// 路由守卫，权限验证
router.beforeEach((to, from, next) => {
  const userStore = useUserStore();

  // 登录和注册页面不需要验证
  if (to.path === "/login" || to.path === "/register") {
    next();
    return;
  }

  // 检查是否需要登录
  if (to.meta.requireAuth && !userStore.isLoggedIn) {
    next("/login");
    return;
  }

  // 如果已登录且访问登录页，重定向到首页
  if (to.path === "/login" && userStore.isLoggedIn) {
    next("/");
    return;
  }

  next();
});

export default router;
